package com.mimo.comet.config;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.mimo.common.rpc.proto.LogicRoomProxyGrpc;
import com.mimo.common.rpc.proto.LogicRoomProxyGrpc.LogicRoomProxyBlockingStub;

import io.grpc.netty.shaded.io.netty.util.internal.ThreadLocalRandom;
import net.devh.boot.grpc.client.inject.GrpcClient;

@Component
public class LogicRoomPoolFactory {

  private final List<LogicRoomProxyGrpc.LogicRoomProxyBlockingStub> holder = new ArrayList<>();

  @PostConstruct
  public void init() throws IllegalAccessException {
    Field[] fields = this.getClass().getDeclaredFields();
    for (Field f : fields) {
      f.setAccessible(true);
      if (f.getType() == LogicRoomProxyGrpc.LogicRoomProxyBlockingStub.class) {
        holder.add((LogicRoomProxyBlockingStub) f.get(this));
      }
    }
  }

  @GrpcClient(value = "logic-room-1")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub1;

  @GrpcClient(value = "logic-room-2")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub2;

  @GrpcClient(value = "logic-room-3")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub3;

  @GrpcClient(value = "logic-room-4")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub4;

  @GrpcClient(value = "logic-room-5")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub5;

  @GrpcClient(value = "logic-room-6")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub6;

  @GrpcClient(value = "logic-room-7")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub7;

  @GrpcClient(value = "logic-room-8")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub8;

  @GrpcClient(value = "logic-room-9")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub9;

  @GrpcClient(value = "logic-room-10")
  private LogicRoomProxyGrpc.LogicRoomProxyBlockingStub logicRoomProxyBlockingStub10;

  public LogicRoomProxyGrpc.LogicRoomProxyBlockingStub getLogicRoomStub() {
    return holder.get(ThreadLocalRandom.current().nextInt(holder.size()));
  }
}
